#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将filter_data中的TXT文件转换为CSV格式
"""

import csv
import os


class TxtToCsvConverter:
    """TXT转CSV转换器"""
    
    def __init__(self):
        self.input_dir = "../filter_data/100"
        self.output_dir = "../filter_data_csv/100"
        self.delimiter = '€€'  # TXT文件的分隔符
        
        # 定义每个文件的列名
        self.headers = {
            'user.txt': [
                'MSISDN', 'USER_ID', 'NEW_RCN_ID', 'RCN_DURA', 
                'IDTY_NBR', 'STATIS_YMD', 'PROV_ID'
            ],
            'call.txt': [
                'MSISDN', 'OPP_MSISDN', 'STATIS_YMD', 'PROV_ID'
            ],
            'tv.txt': [
                'USER_ID', 'MSISDN',
                'IS_PRETTY_NUM', 'PRETTY_NUM_TYP', 'VIP_CUST_ID', 'VIP_LVL',
                'AGE_LVL', 'SEX', 'OCPN_CODE', 'EDUCAT_DEGREE_CODE',
                'BRAND_ID', 'RCN_CHNL_TYP', 'IS_CAMP_USER', 'IS_CAMP_AREA_USER',
                'IS_GROUP_USER', 'MEMB_TYP', 'IS_GROUP_KEY_INDV',
                'IS_GSM_USER', 'GSM_USER_LVL', 'INNET_DURA_LVL_CODE', 'USER_AREA_BELO',
                'ONNET_ALL_FLUX', 'WDAY_ONNET_FLUX', 'NWDAY_ONNET_FLUX',
                'ONNET_FLUX_3G', 'ONNET_FLUX_4G', 'TOT_FLUX_5G',
                'FLUX_FEE', 'FLUX_FEE_4G', 'FLUX_TOT_FEE_5G',
                'CHARGE_PACKAGE_UNIFY_CODE', 'CHARGE_PACKAGE_TYP', 'PACK_MON', 'PACKAGE_5G_ID'
            ]
        }
    
    def convert_file(self, txt_filename: str):
        """转换单个文件"""
        input_path = os.path.join(self.input_dir, txt_filename)
        csv_filename = txt_filename.replace('.txt', '.csv')
        output_path = os.path.join(self.output_dir, csv_filename)
        
        if not os.path.exists(input_path):
            print(f"  ✗ 文件不存在: {txt_filename}")
            return
        
        row_count = 0
        headers = self.headers.get(txt_filename, [])
        
        with open(input_path, 'r', encoding='utf-8') as infile, \
             open(output_path, 'w', encoding='utf-8', newline='') as outfile:
            
            writer = csv.writer(outfile)
            
            # 写入表头
            if headers:
                writer.writerow(headers)
            
            # 转换数据行
            for line in infile:
                line = line.strip()
                if not line:
                    continue
                
                # 按分隔符拆分
                fields = line.split(self.delimiter)
                writer.writerow(fields)
                row_count += 1
        
        print(f"  ✓ {txt_filename} -> {csv_filename}: {row_count:,} 条记录")
    
    def run(self):
        """执行转换"""
        # 创建输出目录
        os.makedirs(self.output_dir, exist_ok=True)
        
        print("=" * 60)
        print("开始转换 TXT 文件为 CSV 格式")
        print(f"输入目录: {self.input_dir}")
        print(f"输出目录: {self.output_dir}")
        print("=" * 60)
        print()
        
        # 转换三个文件
        for filename in ['user.txt', 'call.txt', 'tv.txt']:
            self.convert_file(filename)
        
        print()
        print("=" * 60)
        print("转换完成!")
        print("=" * 60)


def main():
    """主函数"""
    converter = TxtToCsvConverter()
    converter.run()


if __name__ == "__main__":
    main()